package com.yoomiito.app.share.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.ShareViewData
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.shareview.ShareViewManager
import com.yoomiito.app.utils.AllUtils
import com.yoomiito.app.utils.Const
import com.yoomiito.app.utils.ImageLoader
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.wx.UMengShareUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.act_share_1.*
import kotlinx.android.synthetic.main.item_wx_share.*
import kotlinx.android.synthetic.main.title_bar.*
import java.util.concurrent.TimeUnit

class ShareActivity : BaseActivity<SharePresenter>() {

    companion object {
        fun start(context: Context, data: ShareViewData) {
            val intent = Intent(context, ShareActivity::class.java)
            intent.putExtra(Const.Common.Data, data)
            context.startActivity(intent)
        }
    }

    private var disposable: Disposable? = null
    private lateinit var data: ShareViewData
    private var bitmap: Bitmap? = null
    private var startInitView = false
    override fun getLayoutId(): Int = R.layout.act_share_1

    override fun newP(): SharePresenter = SharePresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        data = intent.getSerializableExtra(Const.Common.Data) as ShareViewData
        iv_back_left.setOnClickListener { finish() }
        tv_center.text = "分享红包"
        tv_center.paint.isFakeBoldText = true

        item_share_wx.setOnClickListener {
            UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN, this, bitmap)
        }
        item_share_dynamic.setOnClickListener {
            UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE, this, bitmap)
        }
        item_share_photo.setOnClickListener {
            requestPermission()
        }
        showLoading()
        L.i("开始倒计时 $disposable")
        startWelcome(5)
    }

    private fun initAdView() {
        startInitView = true
        ShareViewManager.instance
                .init(this, ShareViewManager.MeiTuan, data.url[0])
                .onPicMakeListener = { view, bitmap ->
            disposable()
            this.bitmap = bitmap
            iv.setImageBitmap(bitmap)
            dismissLoading()
        }
    }

    private fun startWelcome(time: Int) {
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(time + 1.toLong())
                .map { aLong: Long -> time - aLong }
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { aLong: Long ->
                    if (!startInitView) {
                        initAdView()
                    }
                }
                .doOnComplete {
                    //                    dispose();
                    if (bitmap == null) {
                        finish()
                    }
                }
                .subscribe()
        L.i("开始倒计时11 $disposable")

    }

    private fun disposable() {
        if (disposable != null) {
            if (!disposable?.isDisposed!!) {
                disposable?.dispose()
                disposable = null
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable()
    }

    fun requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            AllUtils.requestPermission2(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe { per ->
                        when {
                            per.granted -> {
                                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                                        checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                                    loadPic()
                                } else {
                                    "请去设置中开启存储读写权限".showToast()
                                }
                            }
                            per.shouldShowRequestPermissionRationale -> {

                            }
                            else -> {
                                "请去设置中开启存储读写权限".showToast()
                            }
                        }
                    }
        } else {
            loadPic()
        }
    }

    private fun loadPic() {
        ImageLoader.getInstance().downloadPic(this, bitmap)
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
    }
}